﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Data.Sql;

namespace CodeGenerator
{
    class Utility
    {
        public static List<Table> currentTables = null;

        private static string MapCSharpToDbType(string csharpType)
        {
            string loweredType = csharpType.ToLower();

            if (loweredType == "int")
                return "int";
            else if (loweredType == "string")
                return "nvarchar";
            else if (loweredType == "DateTime")
                return "datetime";
            else if (loweredType == "bool")
                return "bit";
            else if (loweredType == "double")
                return "decimal";
            else
                return null;
        }

        private static string MapDefaultValue(string dataType)
        {
            string loweredType = dataType.ToLower();

            if (loweredType == "int")
                return "0";
            else if (loweredType == "nvarchar")
                return "string.Empty";
            else if (loweredType == "datetime")
                return "SqlDateTime.MinValue.Value";
            else if (loweredType == "bit")
                return "false";
            else if (loweredType.Contains("decimal"))
                return "0.00";
            else
                return null;
        }

        private static string MapSqlDbType(string dataType)
        {
            string loweredType = dataType.ToLower();

            if (loweredType == "int")
                return SqlDbType.Int.ToString();
            else if (loweredType == "nvarchar")
                return SqlDbType.NVarChar.ToString();
            else if (loweredType == "datetime")
                return SqlDbType.DateTime.ToString();
            else if (loweredType == "bit")
                return SqlDbType.Bit.ToString();
            else if (loweredType.Contains("decimal"))
                return SqlDbType.Decimal.ToString();
            else
                return null;
        }

        private static string MapDbTypeToCSharp(string dbType)
        {
            string loweredType = dbType.ToLower();

            if (loweredType == "int")
                return "int";
            else if (loweredType == "nvarchar")
                return "string";
            else if (loweredType == "datetime")
                return "DateTime";
            else if (loweredType == "bit")
                return "bool";
            else if (loweredType.Contains("decimal"))
                return "double";
            else
                return null;
        }

        private static string MapCSharpFullType(string dbType)
        {
            string loweredType = dbType.ToLower();
            if (loweredType == "int")
                return "Integer";
            else if (loweredType == "bit")
                return "Boolean";
            else if (loweredType == "nvarchar")
                return "String";
            else if (loweredType == "datetime")
                return "DateTime";
            else if (loweredType.Contains("decimal"))
                return "Double";
            else
                return null;
        }

        public static string MapPath(string relativePath)
        {
            string projectRoot = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo directoryInfo = new DirectoryInfo(projectRoot);
            projectRoot = directoryInfo.Parent.Parent.FullName;

            if (!string.IsNullOrEmpty(relativePath))
            {
                relativePath = relativePath.Replace("~", string.Empty).Replace("/", "\\");
                return projectRoot + relativePath;
            }
            else
                return projectRoot;
        }

        public static string TemplateFolder
        {
            get { return MapPath("~/templates"); }
        }

        public static string ORMFolder
        {
            get { return MapPath("~/output/orm"); }
        }

        public static string SPFolder
        {
            get { return MapPath("~/output/sp"); }
        }

        public static string PageFolder
        {
            get { return MapPath("~/output/page"); }
        }

        public static bool WriteFile(string fileContent, string path)
        {
            try
            {
                StreamWriter writer = new StreamWriter(path);
                writer.AutoFlush = true;
                writer.Write(fileContent);
                writer.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool WriteSP(string fileContent)
        {
            return WriteFile(fileContent, SPFolder + "\\stored-procedures.sql");
        }

        public static bool WriteORM(string fileContent, string fileName)
        {
            return WriteFile(fileContent, ORMFolder + "\\" + fileName + ".cs");
        }

        public static bool WritePage(string fileContent, string fileName, string extension)
        {
            if (string.IsNullOrEmpty(extension))
                return WriteFile(fileContent, PageFolder + "\\" + fileName + ".aspx");
            else
                return WriteFile(fileContent, PageFolder + "\\" + fileName + extension);
        }

        public static string ReadTemplate(string fileName)
        {
            FileInfo fileInfo = new FileInfo(MapPath(fileName));
            if (fileInfo.Exists)
                return File.ReadAllText(fileInfo.FullName);
            else
                return null;
        }

        public static List<string> SqlServers
        {
            get
            {
                List<string> serverNames = new List<string>();
                DataTable tblServers = SqlDataSourceEnumerator.Instance.GetDataSources();

                foreach (DataRow row in tblServers.Rows)
                {
                    serverNames.Add(row["ServerName"].ToString() + "\\" + row["InstanceName"].ToString());
                }
                return serverNames;
            }
        }

        public static List<string> Databases(string serverName)
        {
            SqlConnection connection = null;
            try
            {
                List<string> databaseNames = new List<string>();
                connection = ConnectToSqlServer(serverName);
                connection.Open();

                DataTable tblDatabases = connection.GetSchema("Databases");
                connection.Close();

                foreach (DataRow row in tblDatabases.Rows)
                {
                    databaseNames.Add(row["database_name"].ToString());
                }

                return databaseNames;
            }
            catch (SqlException ex)
            {
                return new List<string>();
            }
            catch (Exception ex)
            {
                return new List<string>();
            }
            finally
            {
                connection.Close();
            }
        }

        public static SqlConnection ConnectToSqlServer(string serverName)
        {
            SqlConnection connection = new SqlConnection();
            StringBuilder connectionString = new StringBuilder();
            connectionString.Append("Data Source=").Append(serverName).Append("; Integrated Security=True;");
            connection.ConnectionString = connectionString.ToString();

            return connection;
        }

        public static SqlConnection ConnectToSqlServer(string serverName, string databaseName)
        {
            SqlConnection connection = new SqlConnection();
            StringBuilder connectionString = new StringBuilder();
            connectionString.Append("Data Source=").Append(serverName).Append(";Initial Catalog = ").Append(databaseName).Append("; Integrated Security=True;");
            connection.ConnectionString = connectionString.ToString();

            return connection;
        }

        private static TableColumn ReadTableColumn(SqlDataReader reader)
        {
            string columnName = reader["column_name"] == System.DBNull.Value ? string.Empty : reader["column_name"].ToString();
            string dataType = reader["data_type"] == System.DBNull.Value ? string.Empty : reader["data_type"].ToString();
            int characterMaximumLength = reader["character_maximum_length"] == System.DBNull.Value ? 0 : (int)reader["character_maximum_length"];
            
            if (dataType == "decimal")
                dataType = "decimal(18,2)";

            TableColumn tableColumn = new TableColumn(columnName, dataType, characterMaximumLength);
            return tableColumn;
        }

        public static List<Table> Tables(string serverName, string databaseName)
        {
            SqlCommand command = null;
            SqlDataReader reader = null;
            try
            {
                SqlConnection connection = ConnectToSqlServer(serverName, databaseName);

                string sql = @"SELECT table_name, column_name, data_type, character_maximum_length
                            FROM information_schema.columns
                            WHERE table_name IN
                          (
                            SELECT table_name
                            FROM Information_Schema.Tables
                            WHERE Table_Type='Base Table'
                            AND table_name LIKE 'tbl_%'
                          ) ORDER BY table_name;";

                command = connection.CreateCommand();
                command.CommandText = sql;
                command.Connection.Open();
                reader = command.ExecuteReader();

                List<Table> tables = new List<Table>();
                Table lastTable = null;
                while (reader.Read())
                {
                    string tableName = reader["table_name"] == null ? string.Empty : reader["table_name"].ToString();
                    if (lastTable != null)
                    {
                        if (tableName == lastTable.TableName)
                        {
                            TableColumn tableColumn = ReadTableColumn(reader);
                            lastTable.Columns.Add(tableColumn);
                        }
                        else
                        {
                            List<TableColumn> tableColumns = new List<TableColumn>();

                            TableColumn tableColumn = ReadTableColumn(reader);
                            tableColumns.Add(tableColumn);
                            Table table = new Table(tableName, tableColumns);
                            tables.Add(lastTable);
                            lastTable = table;
                        }
                    }
                    else
                    {
                        List<TableColumn> tableColumns = new List<TableColumn>();

                        TableColumn tableColumn = ReadTableColumn(reader);
                        tableColumns.Add(tableColumn);
                        Table table = new Table(tableName, tableColumns);
                        lastTable = table;
                    }
                }
                if (lastTable != null)
                    tables.Add(lastTable);

                currentTables = tables;
                return tables;
            }
            catch (SqlException ex)
            {
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (!reader.IsClosed)
                    reader.Close();
                command.Connection.Close();
            }
        }

        private static string ORMName(string tableName)
        {
            StringBuilder result = new StringBuilder(tableName);

            for (int i = 0; i < result.Length; i++)
            {
                if (result[i] == '_')
                {
                    result[i + 1] = Char.ToUpper(result[i + 1]);
                    result.Remove(i, 1);
                }
                if (i == 0)
                    result[i] = Char.ToUpper(result[i]);
            }
            return result.Replace("Tbl", string.Empty).ToString();
        }

        private static string GeneratePrivateFields(Table table)
        {
            StringBuilder privateFileds = new StringBuilder(string.Empty);
            foreach (TableColumn column in table.Columns)
            {
                privateFileds.Append("private ").Append(MapDbTypeToCSharp(column.DataType)).Append(" _").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(";\n\t\t");
            }
            if (privateFileds.Length >= 3)
                return privateFileds.Remove(privateFileds.Length - 3, 3).ToString();
            else
                return privateFileds.ToString();
        }

        private static string GenerateProperties(Table table)
        {
            StringBuilder properties = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                string camelCaseName = CodeWork.Library.Utility.ToCamelCase(column.ColumnName);
                properties.Append("public ").Append(MapDbTypeToCSharp(column.DataType)).Append(" ").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append("\n\t\t{\n\t\t\tget { return this._").Append(camelCaseName).Append("; }\n\t\t\tset { this._").Append(camelCaseName).Append(" = value; }\n\t\t}\n\n\t\t");
            }
            if (properties.Length >= 4)
                return properties.Remove(properties.Length - 4, 4).ToString();
            else
                return properties.ToString();
        }

        private static string GeneratePrivateParameterComments(Table table)
        {
            StringBuilder privateParameterComments = new StringBuilder(string.Empty);
            foreach (TableColumn column in table.Columns)
            {
                privateParameterComments.Append("/// <param name=\"").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append("\"></param>\n\t\t");
            }
            if (privateParameterComments.Length >= 3)
                return privateParameterComments.Remove(privateParameterComments.Length - 3, 3).ToString();
            else
                return privateParameterComments.ToString();
        }

        private static string GeneratePrivateParameterCommentsWithoutId(Table table)
        {
            StringBuilder privateParameterComments = new StringBuilder(string.Empty);
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                    privateParameterComments.Append("/// <param name=\"").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append("\"></param>\n\t\t");
            }
            if (privateParameterComments.Length >= 3)
                return privateParameterComments.Remove(privateParameterComments.Length - 3, 3).ToString();
            else
                return privateParameterComments.ToString();
        }

        private static string GeneratePrivateParameters(Table table)
        {
            StringBuilder privateParameters = new StringBuilder(string.Empty);
            foreach (TableColumn column in table.Columns)
            {
                privateParameters.Append(MapDbTypeToCSharp(column.DataType)).Append(" ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(",\n\t\t\t");
            }
            if (privateParameters.Length >= 5)
                return privateParameters.Remove(privateParameters.Length - 5, 5).ToString();
            else
                return privateParameters.ToString();
        }

        private static string GeneratePrivateParametersWithoutId(Table table)
        {
            StringBuilder privateParameters = new StringBuilder(string.Empty);
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                    privateParameters.Append(MapDbTypeToCSharp(column.DataType)).Append(" ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(",\n\t\t\t");
            }
            if (privateParameters.Length >= 5)
                return privateParameters.Remove(privateParameters.Length - 5, 5).ToString();
            else
                return privateParameters.ToString();
        }

        private static string GeneratePrivateParameterAssignments(Table table)
        {
            StringBuilder privateParameterAssignments = new StringBuilder(string.Empty);
            foreach (TableColumn column in table.Columns)
            {
                privateParameterAssignments.Append("this._").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(" = ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(";\n\t\t\t");
            }
            if (privateParameterAssignments.Length >= 4)
                return privateParameterAssignments.Remove(privateParameterAssignments.Length - 4, 4).ToString();
            else
                return privateParameterAssignments.ToString();
        }

        private static string GeneratePrivateParameterAssignmentsWithoutId(Table table)
        {
            StringBuilder privateParameterAssignments = new StringBuilder(string.Empty);
            string tableNameCamel = CodeWork.Library.Utility.ToCamelCase(ORMName(table.TableName));
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                    privateParameterAssignments.Append(tableNameCamel).Append(".").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(" = ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(";\n\t\t\t");
            }
            if (privateParameterAssignments.Length >= 4)
                return privateParameterAssignments.Remove(privateParameterAssignments.Length - 4, 4).ToString();
            else
                return privateParameterAssignments.ToString();
        }

        private static string GeneratePropertyAssignments(Table table)
        {
            StringBuilder propertyAssignments = new StringBuilder(string.Empty);
            string tableNameCamel = CodeWork.Library.Utility.ToCamelCase(ORMName(table.TableName));
            foreach (TableColumn column in table.Columns)
            {
                propertyAssignments.Append(tableNameCamel).Append(".").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(" = ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(";\n\t\t\t");
            }
            if (propertyAssignments.Length >= 4)
                return propertyAssignments.Remove(propertyAssignments.Length - 4, 4).ToString();
            else
                return propertyAssignments.ToString();
        }

        private static string GenerateCommandParameter(Table table)
        {
            StringBuilder commandParameter = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                commandParameter.Append("AddCommandParameter(command, \"@").Append(columnNameHungarian).Append("\", SqlDbType.").Append(MapSqlDbType(column.DataType)).Append(", ").Append(column.CharacterMaximumLength.ToString()).Append(", ParameterDirection.Input, ").Append(columnNameHungarian).Append(");\n\t\t\t");
            }
            if (commandParameter.Length >= 4)
                return commandParameter.Remove(commandParameter.Length - 4, 4).ToString();
            else
                return commandParameter.ToString();
        }

        private static string GenerateCommandParameterWithoutId(Table table)
        {
            StringBuilder commandParameter = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                {
                    string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                    commandParameter.Append("AddCommandParameter(command, \"@").Append(columnNameHungarian).Append("\", SqlDbType.").Append(MapSqlDbType(column.DataType)).Append(", ").Append(column.CharacterMaximumLength.ToString()).Append(", ParameterDirection.Input, ").Append(columnNameHungarian).Append(");\n\t\t\t");
                }
            }
            if (commandParameter.Length >= 4)
                return commandParameter.Remove(commandParameter.Length - 4, 4).ToString();
            else
                return commandParameter.ToString();
        }

        private static string GenerateNewCommandParameter(Table table)
        {
            StringBuilder commandParameter = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                {
                    string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                    commandParameter.Append("AddCommandParameter(command, \"@New").Append(columnNameHungarian).Append("\", SqlDbType.").Append(MapSqlDbType(column.DataType)).Append(", ").Append(column.CharacterMaximumLength.ToString()).Append(", ParameterDirection.Input, ").Append(columnNameHungarian).Append(");\n\t\t\t");
                }
            }
            if (commandParameter.Length >= 4)
                return commandParameter.Remove(commandParameter.Length - 4, 4).ToString();
            else
                return commandParameter.ToString();
        }

        private static string GenerateCopyParameters(Table table)
        {
            StringBuilder copyParameterAssignments = new StringBuilder(string.Empty);
            string tableNameCamel = CodeWork.Library.Utility.ToCamelCase(ORMName(table.TableName));
            foreach (TableColumn column in table.Columns)
            {
                copyParameterAssignments.Append("this._").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(" = ").Append(tableNameCamel).Append("._").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(";\n\t\t\t\t");
            }
            if (copyParameterAssignments.Length >= 5)
                return copyParameterAssignments.Remove(copyParameterAssignments.Length - 5, 5).ToString();
            else
                return copyParameterAssignments.ToString();
        }

        private static string GenerateConditionalParameters(Table table)
        {
            StringBuilder conditionalParameters = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                conditionalParameters.Append("object ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(" = null").Append(";\n\t\t\t");
            }
            if (conditionalParameters.Length >= 4)
                return conditionalParameters.Remove(conditionalParameters.Length - 4, 4).ToString();
            else
                return conditionalParameters.ToString();
        }

        private static string GenerateConditionalAssignment(Table table)
        {
            StringBuilder conditionalAssignment = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                    conditionalAssignment.Append("else if (fieldName == TableColumns.").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(".ToString())").Append("\n\t\t\t\t\t").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(" = conditions[i].Value;\n\t\t\t\t");
            }
            if (conditionalAssignment.Length >= 5)
                return conditionalAssignment.Remove(conditionalAssignment.Length - 5, 5).ToString();
            else
                return conditionalAssignment.ToString();
        }

        private static string GenerateConditionalCommandParameter(Table table)
        {
            StringBuilder commandParameter = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                commandParameter.Append("AddCommandParameter(command, \"@").Append(columnNameHungarian).Append("\", SqlDbType.").Append(MapSqlDbType(column.DataType)).Append(", ").Append(column.CharacterMaximumLength.ToString()).Append(", ParameterDirection.Input, ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(");\n\t\t\t");
            }
            if (commandParameter.Length >= 4)
                return commandParameter.Remove(commandParameter.Length - 4, 4).ToString();
            else
                return commandParameter.ToString();
        }

        private static string CheckDecimal(string mappedType, string columnName)
        {
            StringBuilder castBuilder = new StringBuilder();
            if (mappedType == "double")
                return castBuilder.Append("Convert.ToDouble(reader[\"").Append(columnName).Append("\"])").ToString();
            else
                return castBuilder.Append("(").Append(mappedType).Append(")reader[\"").Append(columnName).Append("\"]").ToString();
        }

        private static string GenerateDataReturnParameters(Table table)
        {
            StringBuilder dataReturnParameter = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                    dataReturnParameter.Append("reader[\"").Append(column.ColumnName).Append("\"] == System.DBNull.Value ? ").Append(MapDefaultValue(column.DataType)).Append(" : ").Append(CheckDecimal(MapDbTypeToCSharp(column.DataType),column.ColumnName)).Append(",\n\t\t\t\t\t");
            }
            if (dataReturnParameter.Length >= 7)
                return dataReturnParameter.Remove(dataReturnParameter.Length - 7, 7).ToString();
            else
                return dataReturnParameter.ToString();
        }

        private static string GenerateTableColumnEnum(Table table)
        {
            StringBuilder tableColumnEnum = new StringBuilder(string.Empty);

            int counter = 0;
            foreach (TableColumn column in table.Columns)
            {
                tableColumnEnum.Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(" = ").Append(counter.ToString()).Append(",\n\t\t\t");
                counter++;
            }
            if (tableColumnEnum.Length >= 5)
                return tableColumnEnum.Remove(tableColumnEnum.Length - 5, 5).ToString();
            else
                return tableColumnEnum.ToString();
        }

        public static List<TableRelation> GetParentTableList(string ormName)
        {
            List<TableRelation> relations = new List<TableRelation>();
            foreach (Table table in currentTables)
            {
                foreach (TableColumn column in table.Columns)
                {
                    if (column.ColumnName.Contains(ormName.ToLower() + "_id"))
                    {
                        string parentTable = column.ColumnName;
                        parentTable = parentTable.Remove(parentTable.Length - 3);
                        parentTable = parentTable.Substring(parentTable.LastIndexOf('_') + 1);

                        relations.Add(new TableRelation(ORMName(parentTable), ORMName(table.TableName), column.ColumnName));
                    }
                }
            }
            return relations;
        }

        private static string GenerateForeignField(TableRelation relation)
        {
            StringBuilder foreignField = new StringBuilder(string.Empty);
            string variableNameHungarian = ORMName(relation.RelationColumnName.Split('_')[0] + relation.ChildTableName);
            string variableNameCamel = CodeWork.Library.Utility.ToCamelCase(variableNameHungarian);
            foreignField = foreignField.Append("private List<").Append(relation.ChildTableName).Append("> _").Append(variableNameCamel).Append(";\n\t\t").Append("private bool _is").Append(variableNameHungarian).Append("Loaded;\n\t\t");
            return foreignField.ToString();
        }

        private static string GenerateForeignKeyProperty(TableRelation relation)
        {
            StringBuilder foreignKeyProperty = new StringBuilder(string.Empty);
            string variableNameHungarian = ORMName(relation.RelationColumnName.Split('_')[0] + relation.ChildTableName);
            string variableNameCamel = CodeWork.Library.Utility.ToCamelCase(variableNameHungarian);
            foreignKeyProperty = foreignKeyProperty.Append("public List<").Append(relation.ChildTableName).Append("> ").Append(variableNameHungarian).Append("\n\t\t").Append("{\n\t\t\t").Append("get\n\t\t\t").Append("{\n\t\t\t\t").Append("if (!this._is").Append(variableNameHungarian).Append("Loaded)\n\t\t\t\t").Append("{\n\t\t\t\t\t").Append("List<Condition> conditions = new List<Condition>();\n\t\t\t\t\t").Append("conditions.Add(new Condition(\"").Append(relation.RelationColumnName).Append("\", ConditionOperator.Equal,this._id, JoinOperator.FirstValue));\n\t\t\t\t\t").Append(relation.ChildTableName).Append(" ").Append(CodeWork.Library.Utility.ToCamelCase(relation.ChildTableName)).Append(" = new ").Append(relation.ChildTableName).Append("();\n\t\t\t\t\t").Append("this._").Append(variableNameCamel).Append(" = ").Append(CodeWork.Library.Utility.ToCamelCase(relation.ChildTableName)).Append(".Load(conditions);\n\t\t\t\t\t").Append("this._is").Append(variableNameHungarian).Append("Loaded = true;\n\t\t\t\t").Append("}\n\t\t\t\t").Append("return this._").Append(variableNameCamel).Append(";\n\t\t\t").Append("}\n\t\t\t").Append("set\n\t\t\t").Append("{\n\t\t\t\t").Append("this._").Append(variableNameCamel).Append(" = value;\n\t\t\t\t").Append("this._is").Append(variableNameHungarian).Append("Loaded = true;\n\t\t\t").Append("}\n\t\t").Append("}\n\t\t");
            return foreignKeyProperty.ToString();
        }

        public static string ModifyORMRelation(string templateText, List<TableRelation> relations)
        {
            string finalText = string.Empty;
            StringBuilder privateFieldText = new StringBuilder(string.Empty);
            StringBuilder propertyText = new StringBuilder(string.Empty);

            foreach (TableRelation relation in relations)
            {
                privateFieldText = privateFieldText.Append(GenerateForeignField(relation));
            }
            finalText = templateText.Replace("<#ForeignKeyFields#>", privateFieldText.ToString());

            foreach (TableRelation relation in relations)
            {
                propertyText = propertyText.Append(GenerateForeignKeyProperty(relation));
            }

            finalText = finalText.Replace("<#ForeignKeyProperty#>", propertyText.ToString());

            return finalText;
        }

        internal static bool ModifyORMTemplate(string templateText, Table table, string namespaceName)
        {
            StringBuilder newTemplateText = new StringBuilder(templateText);
            newTemplateText = newTemplateText.Replace("<#TableName#>", table.TableName).Replace("<#Namespace#>",
            namespaceName).Replace("<#ORMName#>", ORMName(table.TableName)).Replace("<#PrivateFields#>",
            GeneratePrivateFields(table)).Replace("<#Properties#>", GenerateProperties(table)).Replace("<#PrivateParameterComment#>",
            GeneratePrivateParameterComments(table)).Replace("<#PrivateParameters#>",
            GeneratePrivateParameters(table)).Replace("<#PrivateParameterAssignments#>",
            GeneratePrivateParameterAssignments(table)).Replace("<#PropertyAssignments#>",
            GeneratePropertyAssignments(table)).Replace("<#ORMNameCamel#>",
            CodeWork.Library.Utility.ToCamelCase(ORMName(table.TableName))).Replace("<#CommandParameter#>",
            GenerateCommandParameter(table)).Replace("<#NewCommandParameter#>",
            GenerateNewCommandParameter(table)).Replace("<#PrivateParameterCommentWithoutId#>",
            GeneratePrivateParameterCommentsWithoutId(table)).Replace("<#PrivateParametersWithoutId#>",
            GeneratePrivateParametersWithoutId(table)).Replace("<#PrivateParameterAssignmentsWithoutId#>",
            GeneratePrivateParameterAssignmentsWithoutId(table)).Replace("<#CommandParameterWithoutId#>",
            GenerateCommandParameterWithoutId(table)).Replace("<#CopyParameters#>",
            GenerateCopyParameters(table)).Replace("<#ConditionalParameters#>",
            GenerateConditionalParameters(table)).Replace("<#ConditionalAssignment#>",
            GenerateConditionalAssignment(table)).Replace("<#ConditionalCommandParameter#>",
            GenerateConditionalCommandParameter(table)).Replace("<#DataReturnParameters#>",
            GenerateDataReturnParameters(table)).Replace("<#TableColumnEnum#>",
            GenerateTableColumnEnum(table));

            List<TableRelation> relations = GetParentTableList(ORMName(table.TableName));

            string finalTemplateText = ModifyORMRelation(newTemplateText.ToString(), relations);

            bool result = WriteORM(finalTemplateText, ORMName(table.TableName));

            return result;
        }

        private static string GenerateSPParameterDeclare(Table table)
        {
            StringBuilder parameterDeclare = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                {
                    parameterDeclare.Append("@").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(" ").Append(column.DataType);
                    if (column.CharacterMaximumLength > 0)
                        parameterDeclare.Append("(").Append(column.CharacterMaximumLength.ToString()).Append(")").Append(",\n\t");
                    else
                        parameterDeclare.Append(",\n\t");
                }
            }
            if (parameterDeclare.Length >= 3)
                return parameterDeclare.Remove(parameterDeclare.Length - 3, 3).ToString();
            else
                return parameterDeclare.ToString();
        }

        private static string GenerateSPColumnName(Table table)
        {
            StringBuilder tableColumnName = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                    tableColumnName.Append(column.ColumnName).Append(",\n\t\t");
            }
            if (tableColumnName.Length >= 4)
                return tableColumnName.Remove(tableColumnName.Length - 4, 4).ToString();
            else
                return tableColumnName.ToString();
        }

        private static string GenerateSPParameterValue(Table table)
        {
            StringBuilder parameterValue = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                    parameterValue.Append("@").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(",\n\t\t");
            }
            if (parameterValue.Length >= 4)
                return parameterValue.Remove(parameterValue.Length - 4, 4).ToString();
            else
                return parameterValue.ToString();
        }

        private static string GenerateSPFilterCondition(Table table)
        {
            StringBuilder filterCondition = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                {
                    string columnNameHungerian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                    filterCondition.Append("IF @").Append(columnNameHungerian).Append(" IS NULL").Append("\n\t\t\t").Append("SET @Condition = REPLACE(@Condition, '= @").Append(columnNameHungerian).Append("', 'IS NULL');").Append("\n\t\t").Append("ELSE").Append("\n\t\t\t").Append("SET @Condition = REPLACE(@Condition, '@").Append(columnNameHungerian).Append("', ");
                    if (column.DataType.ToLower() != "nvarchar")
                    {
                        if (column.DataType.ToLower() == "datetime")
                            filterCondition.Append("'''' + ");

                        filterCondition.Append("CONVERT(nvarchar(50),@").Append(columnNameHungerian).Append(" )");

                        if (column.DataType.ToLower() == "datetime")
                            filterCondition.Append("+ '''');");
                        else
                            filterCondition.Append(");");
                    }
                    else
                    {
                        filterCondition.Append("'''' + @").Append(columnNameHungerian).Append(" + '''');");
                    }
                    filterCondition.Append("\n\n\t\t");
                }
            }
            if (filterCondition.Length >= 4)
                return filterCondition.Remove(filterCondition.Length - 4, 4).ToString();
            else
                return filterCondition.ToString();
        }

        private static string GenerateValueAssignment(Table table)
        {
            StringBuilder valueAssignment = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                    valueAssignment.Append(column.ColumnName).Append(" = @").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(",\n\t");
            }
            if (valueAssignment.Length >= 3)
                return valueAssignment.Remove(valueAssignment.Length - 3, 3).ToString();
            else
                return valueAssignment.ToString();
        }

        private static string GenerateSPNewValueDeclare(Table table)
        {
            StringBuilder newValueDeclare = new StringBuilder(string.Empty);

            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                {
                    newValueDeclare.Append("@New").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(" ").Append(column.DataType);
                    if (column.CharacterMaximumLength > 0)
                        newValueDeclare.Append("(").Append(column.CharacterMaximumLength.ToString()).Append(")").Append(",\n\t");
                    else
                        newValueDeclare.Append(",\n\t");
                }
            }
            if (newValueDeclare.Length >= 3)
                return newValueDeclare.Remove(newValueDeclare.Length - 3, 3).ToString();
            else
                return newValueDeclare.ToString();
        }

        private static string GenerateSPNewValueCondition(Table table)
        {
            StringBuilder newValueCondition = new StringBuilder(string.Empty);

            bool flage = false;
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName != "id")
                {
                    string columnNameHungerian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                    newValueCondition.Append("IF @New").Append(columnNameHungerian).Append(" IS NULL").Append("\n\t\t\t").Append("SET @sql = @sql + ' ").Append(flage ? "," : "").Append(column.ColumnName).Append(" = NULL ';").Append("\n\t\t").Append("ELSE").Append("\n\t\t\t").Append("SET @sql = @sql + ' ").Append(flage ? "," : "").Append(column.ColumnName).Append(" = ' + ");
                    if (column.DataType.ToLower() != "nvarchar")
                    {
                        if (column.DataType.ToLower() == "datetime")
                            newValueCondition.Append("'''' + ");

                        newValueCondition.Append("CONVERT(nvarchar(50),@New").Append(columnNameHungerian).Append(" )");

                        if (column.DataType.ToLower() == "datetime")
                            newValueCondition.Append(" + '''';");
                        else
                            newValueCondition.Append(";");
                    }
                    else
                    {
                        newValueCondition.Append(" '''' + ").Append("@New").Append(columnNameHungerian).Append(" + '''';");
                    }
                    newValueCondition.Append("\n\n\t\t");
                    flage = true;
                }
            }
            if (newValueCondition.Length >= 4)
                return newValueCondition.Remove(newValueCondition.Length - 4, 4).ToString();
            else
                return newValueCondition.ToString();
        }

        internal static bool ModifySPTemplate(string text2)
        {
            StringBuilder finalTemplate = new StringBuilder();
            bool result = true;
            foreach (Table table in currentTables)
            {
                StringBuilder newTemplateText = new StringBuilder(text2);
                newTemplateText = newTemplateText.Replace("<#ORMName#>",
                    ORMName(table.TableName)).Replace("<#TableName#>",
                    table.TableName).Replace("<#ParameterDeclare#>",
                    GenerateSPParameterDeclare(table)).Replace("<#ColumnName#>",
                    GenerateSPColumnName(table)).Replace("<#ParameterValue#>",
                    GenerateSPParameterValue(table)).Replace("<#FilterCondition#>",
                    GenerateSPFilterCondition(table)).Replace("<#ValueAssignment#>",
                    GenerateValueAssignment(table)).Replace("<#NewValueDeclare#>",
                    GenerateSPNewValueDeclare(table)).Replace("<#NewValueCondition#>",
                    GenerateSPNewValueCondition(table));
                finalTemplate.Append(newTemplateText);
            }
            result &= WriteSP(finalTemplate.ToString());
            return result;
        }

        private static string GenerateEditTemplateFields(Table table)
        {
            StringBuilder editTemplateField = new StringBuilder();
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                {
                    editTemplateField = editTemplateField.Append("<div class=\"row\">").Append("\n\t\t\t").Append("<div class=\"col label\">").Append(ORMName(column.ColumnName.Replace('_', ' '))).Append("</div>\n\t\t\t").Append("<div class=\"col seperator\">:</div>\n\t\t\t").Append("<div class=\"col input\">");
                    if (column.DataType.ToLower() == "bit")
                        editTemplateField = editTemplateField.Append("<asp:CheckBox ID=\"cbx").Append(ORMName(column.ColumnName)).Append("\" runat=\"server\" />");
                    else
                        editTemplateField = editTemplateField.Append("<asp:TextBox ID=\"tbx").Append(ORMName(column.ColumnName)).Append("\" runat=\"server\" SkinID=\"GenericTextBox\"></asp:TextBox>");
                    editTemplateField.Append("</div>\n\t\t</div>\n\t\t");
                }
            }
            if (editTemplateField.Length >= 3)
                return editTemplateField.Remove(editTemplateField.Length - 3, 3).ToString();
            else
                return editTemplateField.ToString();
        }

        private static string GeneratePageColumnNameCamel(Table table)
        {
            StringBuilder columnNameCamel = new StringBuilder();
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                {
                    columnNameCamel = columnNameCamel.Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(",\n\t\t\t\t");
                }
            }
            if (columnNameCamel.Length >= 6)
                return columnNameCamel.Remove(columnNameCamel.Length - 6, 6).ToString();
            else
                return columnNameCamel.ToString();
        }

        private static string GenerateEditPageValueSave(Table table)
        {
            StringBuilder valueSave = new StringBuilder();
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                {
                    valueSave = valueSave.Append(MapDbTypeToCSharp(column.DataType)).Append(" ").Append(CodeWork.Library.Utility.ToCamelCase(column.ColumnName)).Append(" = ");
                    if (column.DataType.ToLower() == "bit")
                    {
                        valueSave = valueSave.Append("cbx").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(".Checked;\n\t\t");
                    }
                    else
                    {
                        valueSave = valueSave.Append("Security.Bind").Append(MapCSharpFullType(column.DataType)).Append("Input(tbx").Append(CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName)).Append(".Text, _securityLevel);\n\t\t");
                    }
                }
            }
            if (valueSave.Length >= 3)
                return valueSave.Remove(valueSave.Length - 3, 3).ToString();
            else
                return valueSave.ToString();
        }

        private static string GenerateEditPageLoadData(Table table)
        {
            StringBuilder loadData = new StringBuilder();
            string tableNameCamel = CodeWork.Library.Utility.ToCamelCase(ORMName(table.TableName));
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                {
                    string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                    if (column.DataType.ToLower() == "nvarchar")
                    {
                        loadData = loadData.Append("if (!string.IsNullOrEmpty(").Append(tableNameCamel).Append(".").Append(columnNameHungarian).Append("))\n\t\t\t\t").Append("tbx").Append(columnNameHungarian).Append(".Text = ").Append(tableNameCamel).Append(".").Append(columnNameHungarian).Append(";\n\t\t\t");
                    }
                    else if (column.DataType.ToLower() == "bit")
                    {
                        loadData = loadData.Append("cbx").Append(columnNameHungarian).Append(".Checked = ").Append(tableNameCamel).Append(".").Append(columnNameHungarian).Append(";\n\t\t\t");
                    }
                    else if (column.DataType.ToLower() == "datetime")
                    {
                        loadData = loadData.Append("if (").Append(tableNameCamel).Append(".").Append(columnNameHungarian).Append(" != SqlDateTime.MinValue)").Append("\n\t\t\t\t");
                        loadData = loadData.Append("tbx").Append(columnNameHungarian).Append(".Text = ").Append(tableNameCamel).Append(".").Append(columnNameHungarian).Append(".ToShortDateString();\n\t\t\t");
                    }
                    else
                    {
                        loadData = loadData.Append("tbx").Append(columnNameHungarian).Append(".Text = ").Append(tableNameCamel).Append(".").Append(columnNameHungarian).Append(".ToString();\n\t\t\t");
                    }
                }
            }
            if (loadData.Length >= 4)
                return loadData.Remove(loadData.Length - 4, 4).ToString();
            else
                return loadData.ToString();
        }

        private static string GenerateListGridFields(Table table)
        {
            StringBuilder listGridFields = new StringBuilder();
            foreach (TableColumn column in table.Columns)
            {
                string headerText = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName.Replace('_', ' ')).Replace("Is", string.Empty).Trim();
                headerText = CodeWork.Library.Utility.ToHungarianNotation(headerText);
                string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                if (column.DataType.ToLower() == "bit")
                {
                    listGridFields = listGridFields.Append("<asp:CheckBoxField DataField=\"").Append(columnNameHungarian).Append("\" HeaderText=\"").Append(headerText).Append("\" ItemStyle-HorizontalAlign=\"Center\" SortExpression=\"").Append(column.ColumnName).Append("\" />\n\t\t\t");
                }
                else
                {
                    listGridFields = listGridFields.Append("<asp:BoundField DataField=\"").Append(columnNameHungarian).Append("\" HeaderText=\"").Append(headerText).Append("\" SortExpression=\"").Append(column.ColumnName).Append("\" />\n\t\t\t");
                }
            }
            if (listGridFields.Length >= 4)
                return listGridFields.Remove(listGridFields.Length - 4, 4).ToString();
            else
                return listGridFields.ToString();
        }

        private static string GenerateListPageFilterCondition(Table table)
        {
            StringBuilder filterCondition = new StringBuilder();
            int count = 0;
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                {
                    if (column.DataType.ToLower() == "nvarchar")
                    {
                        string columnNameCamel = CodeWork.Library.Utility.ToCamelCase(column.ColumnName);
                        string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                        filterCondition = filterCondition.Append(MapDbTypeToCSharp(column.DataType)).Append(" ").Append(columnNameCamel).Append(" = Security.Bind").Append(MapCSharpFullType(column.DataType)).Append("Input(tbx").Append(columnNameHungarian).Append(".Text, _securityLevel);\n\t\t");
                        count++;
                    }
                }
            }

            int counter = 0;
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                {
                    if (column.DataType.ToLower() == "nvarchar")
                    {
                        string columnNameCamel = CodeWork.Library.Utility.ToCamelCase(column.ColumnName);
                        string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                        filterCondition = filterCondition.Append("conditions.Add(new Condition(\"").Append(column.ColumnName).Append("\", ConditionOperator.Like, ").Append(columnNameCamel).Append(", JoinOperator.");
                        if (counter == 0)
                            filterCondition = filterCondition.Append("FirstValue));\n\t\t");
                        else
                            filterCondition = filterCondition.Append("And));\n\t\t");

                        counter++;
                    }
                }
            }
            if (filterCondition.Length >= 3)
                return filterCondition.Remove(filterCondition.Length - 3, 3).ToString();
            else
                return filterCondition.ToString();
        }

        private static string GenerateListPageFilterFieldsFirstColumn(Table table)
        {
            StringBuilder filterFields = new StringBuilder();
            int counter = 0;
            foreach (TableColumn column in table.Columns)
            {
                if (column.ColumnName.ToLower() != "id")
                {
                    if (column.DataType.ToLower() == "nvarchar")
                    {
                        if (counter % 2 == 0)
                        {
                            string filedName = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName.Replace('_', ' ')).Replace("Is", string.Empty).Trim();
                            filedName = CodeWork.Library.Utility.ToHungarianNotation(filedName);
                            string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                            filterFields = filterFields.Append("<div class=\"row\">\n\t\t\t\t<div class=\"col genericFilterText\">").Append(filedName).Append("</div>\n\t\t\t\t").Append("<div class=\"col genericFilterSeperator\">:</div>\n\t\t\t\t").Append("<div class=\"col genericFilterInput\">").Append("<asp:TextBox ID=\"tbx").Append(columnNameHungarian).Append("\" runat=\"server\" SkinID=\"GenericFilterTextBox\"></asp:TextBox></div>\n\t\t\t</div>\n\t\t\t");
                        }
                        counter++;
                    }
                }
            }
            if (filterFields.Length > 4)
                return filterFields.Remove(filterFields.Length - 4, 4).ToString();
            else
                return filterFields.ToString();
        }

        private static string GenerateListPageFilterFieldsSecondColumn(Table table)
        {
            StringBuilder filterFields = new StringBuilder();
            int counter = 0;
            foreach (TableColumn column in table.Columns)
            {

                if (column.ColumnName.ToLower() != "id")
                {
                    if (column.DataType.ToLower() == "nvarchar")
                    {
                        if (counter % 2 != 0)
                        {
                            string filedName = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName.Replace('_', ' ')).Replace("Is", string.Empty).Trim();
                            filedName = CodeWork.Library.Utility.ToHungarianNotation(filedName);
                            string columnNameHungarian = CodeWork.Library.Utility.ToHungarianNotation(column.ColumnName);
                            filterFields = filterFields.Append("<div class=\"row\">\n\t\t\t\t<div class=\"col genericFilterText\">").Append(filedName).Append("</div>\n\t\t\t\t").Append("<div class=\"col genericFilterSeperator\">:</div>\n\t\t\t\t").Append("<div class=\"col genericFilterInput\">").Append("<asp:TextBox ID=\"tbx").Append(columnNameHungarian).Append("\" runat=\"server\" SkinID=\"GenericFilterTextBox\"></asp:TextBox></div>\n\t\t\t</div>\n\t\t\t");
                        }
                        counter++;
                    }
                }
            }
            if (filterFields.Length >= 4)
                return filterFields.Remove(filterFields.Length - 4, 4).ToString();
            else
                return filterFields.ToString();
        }

        internal static bool ModifyPageTemplates(string namespaceName)
        {
            StringBuilder editTemplate = new StringBuilder();
            StringBuilder editCodeTemplate = new StringBuilder();
            StringBuilder listTemplate = new StringBuilder();
            StringBuilder listCodeTemplate = new StringBuilder();

            bool result = true;
            foreach (Table table in currentTables)
            {
                editTemplate = new StringBuilder(ReadTemplate("~/templates/Edit.txt"));
                editTemplate = editTemplate.Replace("<#ORMName#>", ORMName(table.TableName)).Replace("<#EditTemplateFields#>",
                    GenerateEditTemplateFields(table));
                result &= WritePage(editTemplate.ToString(), ORMName(table.TableName) + "Edit", null);

                editCodeTemplate = new StringBuilder(ReadTemplate("~/templates/EditCode.txt"));
                editCodeTemplate = editCodeTemplate.Replace("<#ORMName#>", ORMName(table.TableName)).Replace("<#Namespace#>",
                    namespaceName).Replace("<#ORMNameCamel#>",
                    CodeWork.Library.Utility.ToCamelCase(ORMName(table.TableName))).Replace("<#ORMNameLower#>",
                    ORMName(table.TableName).ToLower()).Replace("<#ColumnNameCamel#>",
                    GeneratePageColumnNameCamel(table)).Replace("<#SaveValues#>",
                    GenerateEditPageValueSave(table)).Replace("<#LoadData#>",
                    GenerateEditPageLoadData(table));

                result &= WritePage(editCodeTemplate.ToString(), ORMName(table.TableName) + "Edit", ".aspx.cs");

                listTemplate = new StringBuilder(ReadTemplate("~/templates/List.txt"));
                listTemplate = listTemplate.Replace("<#ORMName#>", ORMName(table.TableName)).Replace("<#ListGridFields#>",
                    GenerateListGridFields(table)).Replace("<#FilterFieldsFirstColumn#>",
                    GenerateListPageFilterFieldsFirstColumn(table)).Replace("<#FilterFieldsSecondColumn#>",
                    GenerateListPageFilterFieldsSecondColumn(table));
                result &= WritePage(listTemplate.ToString(), ORMName(table.TableName) + "List", null);

                listCodeTemplate = new StringBuilder(ReadTemplate("~/templates/ListCode.txt"));
                listCodeTemplate = listCodeTemplate.Replace("<#ORMName#>", ORMName(table.TableName)).Replace("<#Namespace#>",
                    namespaceName).Replace("<#ORMNameCamel#>",
                    CodeWork.Library.Utility.ToCamelCase(ORMName(table.TableName))).Replace("<#ORMNameLower#>",
                    ORMName(table.TableName).ToLower()).Replace("<#FilterCondition#>",
                    GenerateListPageFilterCondition(table));
                result &= WritePage(listCodeTemplate.ToString(), ORMName(table.TableName) + "List", ".aspx.cs");


            }
            return result;
        }
    }
}
